<template>
  <div class="charts-section" v-if="visualizationData">
    <div class="chart-row">
      <div class="chart-container">
        <h3>能力雷达图</h3>
        <div ref="radarChart" class="chart"></div>
      </div>
      <div class="chart-container">
        <h3>评分分布</h3>
        <div ref="barChart" class="chart"></div>
      </div>
    </div>
    <div class="chart-row">
      <div class="chart-container">
        <h3>能力占比</h3>
        <div ref="pieChart" class="chart"></div>
      </div>
      <div class="chart-container">
        <h3>进步轨迹</h3>
        <div ref="lineChart" class="chart"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue';
import * as echarts from 'echarts';

export default {
  name: 'ChartSection',
  props: {
    visualizationData: {
      type: Object,
      default: null
    }
  },
  setup(props) {
    const radarChart = ref(null);
    const barChart = ref(null);
    const pieChart = ref(null);
    const lineChart = ref(null);

    let radarChartInstance = null;
    let barChartInstance = null;
    let pieChartInstance = null;
    let lineChartInstance = null;

    const initCharts = async () => {
      if (!props.visualizationData) return;

      await nextTick();

      try {
        initRadarChart();
        initBarChart();
        initPieChart();
        initLineChart();
      } catch (error) {
        console.error("图表初始化失败:", error);
      }
    };

    const initRadarChart = () => {
      if (!radarChart.value || !props.visualizationData?.radar_chart) return;

      if (radarChartInstance) {
        radarChartInstance.dispose();
      }

      radarChartInstance = echarts.init(radarChart.value);
      const { radar_chart } = props.visualizationData;

      const option = {
        title: {
          text: '能力雷达图',
          left: 'center',
          textStyle: { fontSize: 16, fontWeight: 'bold' }
        },
        radar: {
          indicator: radar_chart.dimensions?.map(dim => ({ name: dim, max: 100 })) || [],
          radius: '60%',
          axisName: { color: '#666' }
        },
        series: [{
          name: '能力评分',
          type: 'radar',
          data: [{
            value: radar_chart.current_scores || [],
            name: '当前水平',
            itemStyle: { color: '#3a86ff' },
            areaStyle: { color: 'rgba(58, 134, 255, 0.2)' }
          }, {
            value: radar_chart.target_scores || [],
            name: '目标水平',
            itemStyle: { color: '#ff6b6b' },
            areaStyle: { color: 'rgba(255, 107, 107, 0.1)' }
          }]
        }]
      };

      radarChartInstance.setOption(option);
    };

    const initBarChart = () => {
      if (!barChart.value || !props.visualizationData?.bar_chart) return;

      if (barChartInstance) {
        barChartInstance.dispose();
      }

      barChartInstance = echarts.init(barChart.value);
      const { bar_chart } = props.visualizationData;

      const option = {
        title: {
          text: '评分分布',
          left: 'center',
          textStyle: { fontSize: 16, fontWeight: 'bold' }
        },
        xAxis: {
          type: 'category',
          data: bar_chart.categories || [],
          axisLabel: { color: '#666' }
        },
        yAxis: {
          type: 'value',
          axisLabel: { color: '#666' }
        },
        series: [{
          data: bar_chart.current_distribution || [],
          type: 'bar',
          name: '当前分布',
          itemStyle: { color: '#8338ec' },
          barWidth: '40%'
        }]
      };

      barChartInstance.setOption(option);
    };

    const initPieChart = () => {
      if (!pieChart.value || !props.visualizationData?.pie_chart) return;

      if (pieChartInstance) {
        pieChartInstance.dispose();
      }

      pieChartInstance = echarts.init(pieChart.value);
      const { pie_chart } = props.visualizationData;

      const data = pie_chart.strength_distribution?.labels?.map((label, index) => ({
        name: label,
        value: pie_chart.strength_distribution.values[index]
      })) || [];

      const option = {
        title: {
          text: '能力占比',
          left: 'center',
          textStyle: { fontSize: 16, fontWeight: 'bold' }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [{
          name: '能力占比',
          type: 'pie',
          radius: '50%',
          data: data,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      };

      pieChartInstance.setOption(option);
    };

    const initLineChart = () => {
      if (!lineChart.value || !props.visualizationData?.line_chart) return;

      if (lineChartInstance) {
        lineChartInstance.dispose();
      }

      lineChartInstance = echarts.init(lineChart.value);
      const { line_chart } = props.visualizationData;

      const option = {
        title: {
          text: '进步轨迹预测',
          left: 'center',
          textStyle: { fontSize: 16, fontWeight: 'bold' }
        },
        xAxis: {
          type: 'category',
          data: line_chart.time_points || [],
          axisLabel: { color: '#666' }
        },
        yAxis: {
          type: 'value',
          axisLabel: { color: '#666' }
        },
        series: [{
          data: line_chart.projected_scores || [],
          type: 'line',
          smooth: true,
          itemStyle: { color: '#28a745' },
          areaStyle: { color: 'rgba(40, 167, 69, 0.1)' }
        }]
      };

      lineChartInstance.setOption(option);
    };

    const handleResize = () => {
      if (radarChartInstance) radarChartInstance.resize();
      if (barChartInstance) barChartInstance.resize();
      if (pieChartInstance) pieChartInstance.resize();
      if (lineChartInstance) lineChartInstance.resize();
    };

    const cleanup = () => {
      if (radarChartInstance) {
        radarChartInstance.dispose();
        radarChartInstance = null;
      }
      if (barChartInstance) {
        barChartInstance.dispose();
        barChartInstance = null;
      }
      if (pieChartInstance) {
        pieChartInstance.dispose();
        pieChartInstance = null;
      }
      if (lineChartInstance) {
        lineChartInstance.dispose();
        lineChartInstance = null;
      }
    };

    onMounted(() => {
      window.addEventListener('resize', handleResize);
      // 如果数据已经存在，立即初始化图表
      if (props.visualizationData) {
        initCharts();
      }
    });

    onUnmounted(() => {
      window.removeEventListener('resize', handleResize);
      cleanup();
    });

    watch(() => props.visualizationData, () => {
      initCharts();
    }, { deep: true });

    return {
      radarChart,
      barChart,
      pieChart,
      lineChart,
      initCharts
    };
  }
};
</script>

<style scoped>
.charts-section {
  margin: 40px 0;
}

.chart-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 30px;
  margin-bottom: 30px;
}

.chart-container {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(58, 134, 255, 0.1);
}

.chart-container h3 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 1.2rem;
  text-align: center;
}

.chart {
  width: 100%;
  height: 300px;
}

@media (max-width: 768px) {
  .chart-row {
    grid-template-columns: 1fr;
  }

  .chart {
    height: 250px;
  }
}
</style>